<template>
  <div class="container" style="height: 100vh;width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>
      <MTitle class="title">
        <template #left>
          所需物料
        </template>
      </MTitle>
      <MTable :headers="tableHeaders" :rows="tableRows" style="margin-top: 20px;" />
    </main>
    <footer>
      <div style=" text-align: center;margin-top: 20px;display: flex;justify-content: space-around;" v-if="!isDisable">
        <MButton @click="makePlan" v-if="isMake">生成并打印</MButton>
        <MButton @click="materialReceive" v-if="isReceive">确认领用</MButton>
        <MButton @click="makeOut" v-if="isReceive">生成出库单</MButton>
      </div>
    </footer>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />

  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../../components/MBreadcrumb.vue"
import MTitle from "../../components/MTitle.vue"
//import MList from "../../components/MList.vue"
import MButton from "../../components/MButton.vue"
//import MInput from "../../components/MInput.vue"
import MMessage from '../../components/MMessage.vue';
import MTable from '../../components/MTable.vue';
//import MDateTime from '../../components/MDateTime.vue';
//import MTag from "../../components/MTag.vue"
import axios from "../../axios/axios"
export default {
  name: "ProduceInfo",
  components: {
    MBreadcrumb,
    MTitle,
    MTable,
    MButton,
    //MInput,
    MMessage,
    //MTag
    //MIcon
  },
  setup() {
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const breadcrumbItem = {
      key: "0",
      title: '赋码管理',
      children: {
        key: "0-0",
        title: '生产计划',
      }
    }

    const tableHeaders = [
      { id: 1, text: '物料名称', width: "28%" },
      { id: 2, text: '规格', width: "36%" },
      { id: 3, text: '数量', width: "18%" },
      { id: 4, text: '库存', width: "18%" }
    ]
    const tableRows = ref([
      ['液晶面板', '75英寸，4K Ultra HD分辨率', '1', "1"],
      ['背光模组', 'LED背光，包含灯条、反射片等', '1', "1"],
      ['驱动电路板', '主控板、电源板等', '0', '0'],
      ['音频电路板', '负责音频处理和输出', '1', '1'],
      ['外壳', '包括前壳、后壳、底座等', '1', '1'],
      ['喇叭', '负责音频播放', '2', '2'],
      ['遥控器', '红外线遥控器', '1', '1'],
      ['电源线', '连接电视和电源插座', '1', '1'],
      ['AV线', '连接电视和音频/视频设备', '1', '1'],
      ['HDMI线', '高清多媒体接口线', '1', '1'],
      ['螺丝及紧固件', '用于固定电视内部和外部组件', '0', '0'],
      ['缓冲材料', '用于保护电视在运输过程中的安全', '0', '0'],
      ['包装材料', '包括纸箱、泡沫、防尘袋等', '1', '1'],
      ['用户手册', '包含使用说明和保修信息', '1', '1'],
      ['其他辅料', '如胶带、标签等', '0', '0']
    ])
    const ProductInfo = ref(["", "", "", "", "", "", ""])
    const tagItems = ref([])
    const params = ref([])
    const userId = ref("")
    const orderInfo = ref({})
    const isMake = ref(false)
    const isReceive = ref(false)
    const isDisable = ref(false)

    const makePlan = () => {
      axios.get("/step/sendstep?type=materialDemand&userId=" + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId')).then(res => {
        if (res.data.Code === "200") {
          messageShow("已生成物料单", "success")
        }
      })
    }
    const makeOut = () => {
      if (orderInfo.value.isreceive === "1") {
        axios.get("/step/sendstep?type=materialOut&userId=" + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId')).then(res => {
          if (res.data.Code === "200") {
            messageShow("已生成出库单", "success")
          }
        })
      } else {
        messageShow("请先领用", "warning")

      }
    }
    const materialReceive = () => {
      if (orderInfo.value.isreceive === "0") {
        axios.post("/material/update", {
          id: orderInfo.value.id,
          isreceive: "1"
        }).then(res => {
          if (res.data.Code === "200") {
            messageShow("领用成功", "success")
            orderInfo.value.isreceive = "1"
          }
        })
      } else {
        messageShow("已领用", "warning")
      }
    }

    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }
      if (param.has('isDisable')) {
        isDisable.value = param.get('isDisable') === "true"
      }
      if (param.get('targetPageId') === "materialDemand") {
        isMake.value = true
      }
      if (param.get('targetPageId') === "materialReceive") {
        isReceive.value = true
      }
      axios.get('/order/select?userId=' + param.get('userId') + "&trainingId=" + param.get('trainingId') + "&isPart=0")
        .then(response => {
          var info = response.data.Data
          axios.get('/produce/selectbyinfo?orderNumber=' + info.ordernumber)
            .then(response => {
              axios.get('/material/select?planNumber=' + response.data.Data.plannumber)
                .then(response1 => {
                  orderInfo.value = response1.data.Data
                  //var infoList=JSON.parse(response1.data.Data.materialinfo)
                  var tableInfo = [...tableRows.value]
                  for (var i = 0; i < tableInfo.length; i++) {
                    if (i === 0) {
                      tableInfo[i][2] = String(Number(tableInfo[i][2]) * info.goodsnumber)
                      tableInfo[i][3] = String(Number(tableInfo[i][3]) * info.goodsnumber)
                      continue
                    }
                    if (tableInfo[i][2] !== "0") {
                      tableInfo[i][2] = String(Number(tableInfo[i][2]) * info.goodsnumber)
                      tableInfo[i][3] = String(Number(tableInfo[i][3]) * info.goodsnumber + 100)
                    } else {
                      tableInfo[i][2] = "若干"
                      tableInfo[i][3] = "若干"
                    }
                  }
                })
            })
        })

    });
    return {
      toastVisible,
      toastMessage,
      toastState,
      breadcrumbItem,
      tagItems,
      ProductInfo,
      tableHeaders,
      tableRows,
      isMake,
      isReceive,
      isDisable,
      makePlan,
      materialReceive,
      makeOut
    };
  },
};
</script>

<style scoped>
.title {
  margin-top: 30px;
}

.title1 {
  margin-top: 20px;
}

.mtr {
  display: flex;
  flex-wrap: wrap;
  /* 允许子元素换行 */
  align-items: flex-start;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
}

main {
  flex: 1;
}

.mtable {
  width: 100%;
  font-size: 13px;

}

.field {
  text-align: left;
  padding: 4px 0;
  flex: 1 1 60px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
  height: 26px;
  line-height: 26px;
}

.value {
  text-align: right;
  padding: 4px 0;
  flex: 1 1 190px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  height: 26px;
  line-height: 26px;
  /* 确保内容可以缩小 */
}
</style>